package com.eastcom.bm.dataprocess.processor;


import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import com.eastcom.canicula.stope.dogrobber.ISwitch;
import com.eastcom.canicula.stope.dogrobber.Messenger;
import com.eastcom.canicula.stope.utils.DateUtil;
import com.eastcom.canicula.stope.utils.MyLogger;

public class KpiMessageSwitch implements ISwitch{
	
	private DataCollector dc = null;
    private long count = 0;
	
    public KpiMessageSwitch(DataCollector dc){
		this.dc = dc;
	}
    
    //private long idbCount = 0;

    public void process(HashMap map) {
        try{
			String type = Messenger.getMessageName((String) map.get("head.typecode"));
			List<KpiMessage> kpis = this.decodeKPIs(map);
            if(kpis != null && kpis.size() > 0){
            	if(type!=null&&type.equals("KPI_COLLECTOR_REQ"))
            		DataCollector.processData(kpis,true);
            	else
            		DataCollector.processData(kpis,false);
            }
            count++;
        }
        catch(Exception e){
        	e.printStackTrace();
            System.out.println("message is :"+map);
            System.out.println("type is :"+(String) map.get("head.typecode"));
            System.out.println("kpi decode error:"+e.getMessage());
			MyLogger.logException(e);
        }      
    }
    
    private List<KpiMessage> decodeKPIsByDatas(Element element,String dataSetId){
    	if(element==null)
    		return null;
    	
    	String dataTime=element.getAttributeValue("datatime");
    	if(dataTime==null||"".equals(dataTime.trim()))
    		return null;
    	
    	List<KpiMessage> kpiMessages=new ArrayList<KpiMessage>();
    	List els = element.getChildren();
    	int neSum=0;
    	Set publicNeSet=new HashSet();
    	
    	for (Iterator it = els.iterator(); it.hasNext();) {
    		Element el = (Element) it.next();
    		if(!"ne".equals(el.getName()))
    			continue;
    		
    		neSum++;
    		String neId=el.getAttributeValue("id");
    		publicNeSet.add(neId);
    		List kpiEls = el.getChildren();
    		for (Iterator ite = kpiEls.iterator(); ite.hasNext();) {
    			Element kpiEl = (Element) ite.next();
    			if("kpi".equals(kpiEl.getName()))
    				kpiMessages.add(new KpiMessage(dataSetId,neId,dataTime,kpiEl));
    		}
    	}
    	
    	String generateTime=null;
    	try{
    		generateTime=DateUtil.DateToString("yyyy-MM-dd HH:mm:ss", new Date());
    	}
    	catch(Exception e){
    		
    	}
    	
    	if(kpiMessages.isEmpty()){
    		KpiMessage kpiMsg=new KpiMessage();
        	kpiMsg.setDataSetId(dataSetId);
        	kpiMsg.setIntegerNeNum(0);
        	kpiMsg.setTimeStamp(dataTime);
        	kpiMsg.setPublicNeSet(publicNeSet);
        	kpiMessages.add(kpiMsg);
    	}
    	else{
    		for(KpiMessage kpiMsg:kpiMessages){
    			kpiMsg.setIntegerNeNum(neSum);
    			kpiMsg.setPublicNeSet(publicNeSet);
    			kpiMsg.setGenerateTime(generateTime);
    		}
    	}
    	
    	return kpiMessages;
    }
    
    public ArrayList<KpiMessage> decodeKPIs(Map map){
        String entity = (String)map.get("body.entity");
        if(entity == null || entity.equals(""))
            return null;
        
        ArrayList<KpiMessage> m = new ArrayList<KpiMessage>();
        
        try{
            Reader r = new StringReader(entity);
            SAXBuilder sb = new SAXBuilder();

            Document d = sb.build(r);
            Element root = d.getRootElement();
            List els = root.getChildren();
            String dataSetId=root.getAttributeValue("id");
            
            for (Iterator i = els.iterator(); i.hasNext();) {
                Element el = (Element) i.next();
                if(!"datas".equals(el.getName()))
                	continue;
                
                List<KpiMessage> kpiMessages=this.decodeKPIsByDatas(el, dataSetId);
                m.addAll(kpiMessages);
            }
            
            
        }
        catch(Exception e){
            System.out.println("*****DataCollector received a invalid kpi_data:"+map);
            //e.printStackTrace();
            System.out.println(e.getMessage());
        }       

        return m;
    }
}

